import axios from 'axios'
import store from '@/store'
import router from '@/router'
import {getToken, removeToken} from './auth'
import * as types from "../../../store/mutation-types";

//创建一个axios实例
const instance = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 10000 // request timeout
})

//request拦截器
instance.interceptors.request.use(config => {
  //匿名访问ID本地缓存
    let storage = window.localStorage;
    let anonymIdDate = new Date()
    let anonymId = ''
    if (storage.getItem("anonymId")) {
      anonymId = storage.getItem("anonymId")
    } else {
      anonymId = 'anonymId' + (anonymIdDate.getTime() + parseInt(Math.random() * 100000000))
      storage.setItem("anonymId", anonymId);
    }
    //未登录状态随机生成一个匿名访问ID，通过请求头的方式发送给服务器
    config.headers.AnonymIdentification = anonymId
    //每次发送请求之前检测都vuex存有token,那么都要放在请求头发送给服务器
    if (store.getters.token) {
      config.headers.Authorization = `bearer ${getToken()}`
      config.headers.AnonymIdentification = ''
    }
    return config;
  },
  err => {
    console.log(err)
    return Promise.reject(err);
  }
);
//respone拦截器
instance.interceptors.response.use(
  response => {
    return response;
  },
  error => { //默认除了2XX之外的都是错误的，就会走这里
    console.log(`err: ${error}`) //for debugger
    if (error.response) {
      switch (error.response.status) {
        case 401:

          store.commit(types.SET_TOKEN, '')   //可能是token过期，清除它
          removeToken()
          let reg = /(home)|(new)|(limited-deals)|(Affiliate)|(hot)|(featured)|(categories)|(activity)/
          let regEx = /(new-)/
          let needLogin = reg.test(router.currentRoute.fullPath) && !regEx.test(router.currentRoute.fullPath)
          console.log(needLogin)
          if (needLogin) break
          router.replace({ //跳转到登录页面
            path: '/sign-in',
            query: {redirect: router.currentRoute.fullPath} // 将跳转的路由path作为参数，登录成功后跳转到该路由
          })
          break

        // case 404:
          // router.push('/error-404')
          // break
        case 500:

          router.push('/error-500')
      }
    }
    // console.log(JSON.stringify(error));//console : Error: Request failed with status code 402
    return Promise.reject(error.response);
  }
);

export default instance;
